import {Component, OnInit} from '@angular/core';
import {BasePage} from '../../common/basePage';
import {AlertController, Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {ActivatedRoute} from '@angular/router';
import {IframePageComponent} from '../../components/iframe-page/iframe-page.component';
import {AppConfig} from '../../common/app-config.enum';

/**
 * 银行卡管理
 */
@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.page.html',
  styleUrls: ['./user-card.page.scss'],
})
export class UserCardPage extends BasePage implements OnInit {

  userRole: string;
  cardList: any[] = [];

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private modalCtrl: ModalController,
              private routeInfo: ActivatedRoute,
              private events: Events,
              private service$: HttpService,
              private alertCtrl: AlertController
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.userRole = this.routeInfo.snapshot.params['userRole'];
    this.getDataList();
  }

  getDataList() {
    this.service$.doRequest(UrlAndOPT.auth_user_card, {userRole: this.userRole})
      .subscribe(obj => {
        if (obj) {
          this.cardList = obj['records'];
        }
      });
  }

  // 确认解除绑定
  async presentAlertConfirm(card: any) {
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '您确定要<strong style="color: #F37938">解除</strong>绑定吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        }, {
          text: '确定',
          handler: () => {
            this.unbindCard(card);
          }
        }
      ]
    });
    await alert.present();
  }

  // 解绑定银行卡 userId cardId deviceType userRole
  unbindCard(cardId: string) {
    this.service$.doRequest(UrlAndOPT.unbind_card, {cardId: cardId})
      .subscribe((obj) => {
        if (obj) {
          this.getDataList(); // 刷新当前面数据
          this.events.publish(AppConfig.TOPIC_UNDO_LIST); // 通知安全中心刷新数据
          this.showToast('银行卡解绑成功！');
        }
      });
  }

  // 新增银行卡
  addCard() {
    this.service$.doRequest(UrlAndOPT.bind_card)
      .subscribe( async (obj) => {
        if (obj) {
          // 打开银行页面model
          const modal = await this.modalCtrl.create({
            component: IframePageComponent,
            componentProps: {
              title: '新增银行卡',
              url: obj['url']
            }
          });
          await modal.present();
          // 关闭model后，刷新当前面数据并通知安全中心刷新数据
          await modal.onDidDismiss();
          this.getDataList();
          this.events.publish(AppConfig.TOPIC_UNDO_LIST);
        }
      });
  }

}
